package com.ysd.alipay.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ysd.alipay.config.AlipayConfig;
import com.ysd.alipay.fegin.OrdersFeginClient;
import com.ysd.common.entity.Orders;

@Controller
@RequestMapping(value="/Alipay")
public class AlipayController {
	
	 @Autowired
	 private OrdersFeginClient ordersFeginClient;
	 String out_trade_no = "";
	/**
	 * 获取订单数据接口
	 * @param WIDout_trade_no
	 * @param WIDtotal_amount
	 * @param WIDsubject
	 * @param request
	 * @param response
	 * @throws AlipayApiException
	 * @throws IOException
	 */
	@RequestMapping(value = "/PayPage")
    public void  payController (HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
		
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		
		
		//商户订单号，商户网站订单系统中唯一订单号，必填
		out_trade_no = request.getParameter("Order");
		 //让订单状态改为1   out_trade_no
        ordersFeginClient.updateFK(Integer.parseInt(out_trade_no));
		//付款金额，必填
		String total_amount = request.getParameter("Money");
		//订单名称，必填
		String subject = request.getParameter("Name");
		//商品描述，可空
		String body = null;
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
		//请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
		
		response.setContentType("text/html;charset=" + AlipayConfig.charset);
		
		response.getWriter().write(result);//直接将完整的表单html输出到页面
		
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/notifyUrl")
	public String notifyUrl(Model model) {
		return "redirect:/";
	}
	
	/**
	 * 支付后的回调路劲
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws AlipayApiException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/returnUrl")
	public String returnUrl(HttpServletRequest request, HttpServletResponse response,Model model) throws AlipayApiException, UnsupportedEncodingException {
		//获取支付宝POST过来反馈信息
		 // 获取支付宝GET过来反馈信息（官方固定代码）
		
		 //让订单状态改为1   out_trade_no
        ordersFeginClient.updateFK(Integer.parseInt(out_trade_no));
		
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名

        // 返回界面
        if (signVerified) {
            System.out.println("前往支付成功页面");
            return "redirect:/";
        } else {
            System.out.println("前往支付失败页面");
            return "redirect:/";
        }
	}
	
	
}
